package com.easy.dfc.Utils;

import com.aliyun.oss.OSSClient;
import com.easy.dfc.entity.*;
import com.easy.dfc.service.OrderActionService;
import com.easy.dfc.service.TiantiantejiaService;
import com.easy.dfc.service.TiaoweihuosetService;
import com.easy.dfc.service.TuangouService;
import org.apache.commons.codec.binary.Hex;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by VULCANTSeries on 2017/5/11.
 */
public class Util {

    private static int ItemNo = 0000;

    public static String privateKeyPath = "F:/development/dfc/dfcservice/dfcapp/src/main/resources/Pingxx-own-private.pem";
    public static String UnixprivateKeyPath = "/var/lib/tomcat8/webapps/ROOT/WEB-INF/classes/Pingxx-own-private.pem";

    public static String publicKeyPath = "F:/development/dfc/dfcservice/dfcapp/src/main/resources/Pingxx-RSA-Public.pem";
    public static String UnixpublicKeyPath = "/var/lib/tomcat8/webapps/ROOT/WEB-INF/classes/Pingxx-RSA-Public.pem";

    public static String accessKeyId = "LTAIY5iOnflkikVC";
    public static String accessKeySecret = "onsgaknWNHzaJr8KDkvctuJUMqOgns";

    public static String endpoint = "http://oss-cn-shanghai.aliyuncs.com";


    public static String SaltPasswd = "Us3W5hKjd73N6QvI4wsMmtg";

    //将C#端返回的id格式变为和数据库一样的格式
    public static String ToUuidString(String Id) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(Id.substring(0, 8))
                .append("-").append(Id.substring(8, 12))
                .append("-").append(Id.substring(12, 16))
                .append("-").append(Id.substring(16, 20))
                .append("-").append(Id.substring(20));
        return stringBuffer.toString();
    }

    //判断该产品是否在活动中，如果在活动中则返回true并改变返回数据中的PromotionStuts状态
    public static boolean PromotionStuts(ProductsetWithBLOBs productsetWithBLOBs, TiantiantejiaService tiantiantejiaService, TiaoweihuosetService tiaoweihuosetService, TuangouService tuangouService) {
        long time = new Date().getTime() / 1000;
        if ("挑尾货".equals(productsetWithBLOBs.getPromotiontype())) {
            List<TiaoweihuosetWithBLOBs> tiaoweihuosetWithBLOBsList = tiaoweihuosetService.getTiaoweihuo(productsetWithBLOBs.getProductid());
            if (tiaoweihuosetWithBLOBsList != null) {
                for (TiaoweihuosetWithBLOBs t : tiaoweihuosetWithBLOBsList) {
                    if (t.getStart() < time && t.getEnd() > time) {
                        productsetWithBLOBs.setPromotionStuts(1);
                        return true;
                    }
                }
            }
        }
        if ("聚爆款".equals(productsetWithBLOBs.getPromotiontype())) {
            List<TiantiantejiaWithBLOBs> tiantiantejiaWithBLOBsList = tiantiantejiaService.getTiantiantejia(productsetWithBLOBs.getProductid());
            if (tiantiantejiaWithBLOBsList != null) {
                for (TiantiantejiaWithBLOBs t : tiantiantejiaWithBLOBsList) {
                    if (t.getStart() < time && t.getEnd() > time) {
                        productsetWithBLOBs.setPromotionStuts(1);
                        return true;
                    }
                }
            }
        }
        if ("团购".equals(productsetWithBLOBs.getPromotiontype())) {
            List<TuangouWithBLOBs> tuangouWithBLOBsList = tuangouService.getTuangou(productsetWithBLOBs.getProductid());
            if (tuangouWithBLOBsList != null) {
                for (TuangouWithBLOBs t : tuangouWithBLOBsList) {
                    if (t.getStart() < time && t.getEnd() > time) {
                        productsetWithBLOBs.setPromotionStuts(1);
                        return true;
                    }
                }
            }
        }
        return false;
    }

    //获取订单号
    public static String getOrderItemNo() {
        String str = "0000" + ItemNo;
        String s = new SimpleDateFormat("yyMMdd").format(new Date()) + (new Random().nextLong() + "").substring(1, 11) + (str).substring(str.length() - 4);
        ItemNo++;
        if (ItemNo >= 10000) {
            ItemNo = 0000;
        }
        return s;
    }

    /**
     * 获取用户真实IP地址，不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * 参考文章： http://developer.51cto.com/art/201111/305181.htm
     * <p>
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值，究竟哪个才是真正的用户端的真实IP呢？
     * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。
     * <p>
     * 如：X-Forwarded-For：192.168.1.110, 192.168.1.120, 192.168.1.130,
     * 192.168.1.100
     * <p>
     * 用户真实IP为： 192.168.1.110
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static String getPrivateKeyPath(HttpServletRequest request) {
        String url = request.getRequestURL().toString();
        if (url.startsWith("http://localhost:8080") || url.startsWith("http://192.168.1.121:8080") || url.startsWith(" http://w6et5g.natappfree.cc")) {
            return privateKeyPath;
        } else if (url.startsWith("http://testjapi.dfcapp.com:8080") || url.startsWith("http://japi.dfcapp.com:8080")) {
            return UnixprivateKeyPath;
        }
        return UnixprivateKeyPath;
    }

    public static String getPublicKeyPath(HttpServletRequest request) {
        String url = request.getRequestURL().toString();
        if (url.startsWith("http://localhost:8080") || url.startsWith("http://192.168.1.121:8080") || url.startsWith(" http://w6et5g.natappfree.cc")) {
            return publicKeyPath;
        } else if (url.startsWith("http://testjapi.dfcapp.com:8080") || url.startsWith("http://japi.dfcapp.com:8080")) {
            return UnixpublicKeyPath;
        }
        return publicKeyPath;
    }

    public static String getApiKey(HttpServletRequest request) {
        String url = request.getRequestURL().toString();
        if (url.startsWith("http://localhost:8080") || url.startsWith("http://192.168.1.121:8080") || url.startsWith("http://testjapi.dfcapp.com:8080") || url.startsWith(" http://w6et5g.natappfree.cc")) {
            return "sk_test_0i18GOHaPm98jnv5y5yDSuHK";
        } else if (url.startsWith("http://japi.dfcapp.com:8080")) {
            return "sk_live_b9SaPCDqrvfDmbnPeHqvL8yD";
        }
        return "sk_test_0i18GOHaPm98jnv5y5yDSuHK";
    }

    //添加订单行为记录
    public static void AddOrderAction(int Id, OrderActionService orderActionService, int status) {
        OrderAction orderAction = new OrderAction();
        orderAction.setAction(status);
        orderAction.setCreatedon(new Date());
        orderAction.setOrderid(Id);
        orderActionService.insertSelective(orderAction);
    }

    // 加密
    public static String getBase64(String str) {
        byte[] b = null;
        String s = null;
        try {
            b = str.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (b != null) {
            s = new BASE64Encoder().encode(b);
        }
        return s;
    }

    // 解密
    public static String getFromBase64(String s) {
        byte[] b = null;
        String result = null;
        if (s != null) {
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                b = decoder.decodeBuffer(s);
                result = new String(b, "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    //OSS上传文件
    public static void OSSUpload(String bucketName, String key, InputStream inputStream) {
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 上传文件流
        ossClient.putObject(bucketName, key + "", inputStream);
        // 关闭client
        ossClient.shutdown();
    }

    public static String getRequestString(String s) {
        if (s == null || "".equals(s)) {
            return null;
        }
        return s;
    }

    public static String UploadImages(HttpServletRequest request, String bucketName) throws IOException {
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();

            while (iter.hasNext()) {
                //一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file != null && file.getSize() > 0) {
                    String key = new Date().getTime() + file.getOriginalFilename();
                    Util.OSSUpload(bucketName, key, file.getInputStream());
                    String path = "http://" + bucketName + ".oss-cn-shanghai.aliyuncs.com/" + key;
                    return path;
                }
            }
        }
        return null;
    }
    public static List<Map<String,String>> UploadImagesList(HttpServletRequest request, String bucketName) throws IOException {
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        List list = new ArrayList();
        if (multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            int trc = 1;
            while (iter.hasNext()) {
                //一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file != null && file.getSize() > 0) {
                    String key = new Date().getTime() + file.getOriginalFilename();
                    Util.OSSUpload(bucketName, key, file.getInputStream());
                    String path = "http://" + trc + bucketName + ".oss-cn-shanghai.aliyuncs.com/" + key;
                    Map<String,String> map = new HashMap<String,String>();
                    map.put("url","");
                    map.put("ossUrl",path);
                    list.add(map);
                    trc ++ ;
                }
            }
        }
        return list;
    }
    public static String getPassword(String password){
        MessageDigest messageDigest;
        String encdeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            byte[] hash = messageDigest.digest((password+SaltPasswd).getBytes("UTF-8"));
            encdeStr = Hex.encodeHexString(hash);
            encdeStr = encdeStr.replaceAll("-","");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encdeStr;
    }
    public static String getToken(String userId,String password){
        MessageDigest messageDigest;
        String encdeStr = "";
        try {
            long time = new Date().getTime();
            String str = userId + password + time + "bY6gdHNQ5efzKUl0m444Cg6P";
            messageDigest = MessageDigest.getInstance("SHA-256");
            byte[] hash = messageDigest.digest((password+SaltPasswd).getBytes("UTF-8"));
            encdeStr = Hex.encodeHexString(hash);
            encdeStr = encdeStr.replaceAll("-","");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encdeStr;
    }
}
